import api, gui, mouseHandler, tones, ui, winUser, wx
from controlTypes.role import Role
timer = None
msgList = None
lastMsg = None
def init():
    # 初始化
    global msgList, timer
    timer = wx.Timer(gui.mainFrame)
    gui.mainFrame.Bind(wx.EVT_TIMER, onTimerEvent, timer)
    reset()
def release ():
    global msgList, timer
    # 释放资源
    if not timer: return
    timer.Stop()
    timer, msgList = None, None
def reset():
    global msgList
    # 用于快捷键朗读消息
    msgList = None
def switchAutoSpeakMsg ():
    # 自动朗读消息开关
    if not timer: return
    tones.beep(800, 50)
    if timer.IsRunning ():
        timer.Stop ()
        ui.message ('已关闭消息自动朗读')
        return
    # 开始自动朗读
    timer.Start (1000)
    ui.message ('已开启消息自动朗读')
def onTimerEvent(event):
    global lastMsg
    # 判断当前窗口是不是 qq
    obj = api.getForegroundObject()
    if obj.windowClassName != 'ChatWnd': return
    # 处理消息自动朗读
    msg = getLastMsg ()
    if lastMsg == msg:return
    lastMsg = msg
    ui.message(msg)
def getMsgList():
    global msgList
    # 获取聊天窗口消息列表，有缓存
    if msgList:
        return msgList
    obj = api.getForegroundObject()
    # 没有获取到窗口对象就直接返回
    if not obj: return
    # 找到消息列表
    for child in obj.recursiveDescendants:
        if child.role != Role.LIST or child.name != '消息': continue
        msgList = child
        return msgList
def getLastMsg ():
    # 获取最后一条消息
    msgList = getMsgList()
    # 如果没有获取到消息列表就直接返回
    if not msgList: return
    # 找到最后一条消息
    return msgList.children[-1].name
def clickButton(name):
    obj = api.getForegroundObject()
    if not obj:
        # 没有获取到窗口对象就直接返回
        tones.beep(500, 50)
        return
    tones.beep(800, 50)
    # 找到按钮
    for child in obj.recursiveDescendants:
        if child.role == Role.BUTTON and child.description == name:
            click(child)
def click(obj):
    # 点击操作
    l, t, w, h = obj.location
    x, y = int(l + w / 2), int(t + h / 2)
    winUser.setCursorPos(x, y)
    mouseHandler.executeMouseMoveEvent(x, y)
    mouseHandler.doPrimaryClick()